﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace Elvex
{
    public class UIStack : MonoBehaviour
    {
        Stack<object> m_stack = new Stack<object>();

        Dictionary<object, UIAsset> m_assets = new Dictionary<object, UIAsset>();

        public UIAsset Push(object id)
        {
            // 记载UI资源
            if (!m_assets.TryGetValue(id, out var asset))
            {
                asset = UIAsset.Load(id, transform);
                if (null == asset)
                {
                    return null;
                }
                m_assets.Add(id, asset);          
            }

            // 关闭上一个界面
            if (m_stack.Count > 0)
            {
                var lastid = m_stack.Peek();
                if (m_assets.TryGetValue(lastid, out var lastasset))
                {
                    lastasset.SetActive(false);
                }
            }

            m_stack.Push(id);
            asset.gameObject.SetActive(true);
            return asset;
        }

        public T Push<T>(object id) where T : Component
        {
            var asset = Push(id);
            var component = asset.GetComponent<T>();
            if (null == component) component = asset.AddComponent<T>();
            return component;
        }

        public void Pop()
        {
            if (m_stack.Count <= 0)
            {
                return;
            }

            var id = m_stack.Pop();
            if(m_assets.TryGetValue(id, out var asset) )
            {
                if(m_stack.Contains(id))
                {
                    asset.SetActive(false);
                }
                else
                {
                    m_assets.Remove(id);
                    Destroy(asset.gameObject);
                }
            }

            if(m_stack.Count > 0 )
            {
                var preid = m_stack.Peek();
                if (m_assets.TryGetValue(preid, out var prego))
                {
                    prego.SetActive(true);
                }
                else
                {
                    Debug.LogFormat("Panel[{0}] is null.");
                }
            }
        }

        public UIAsset Peek()
        {
            if (m_stack.Count < 1)
            {
                return null;
            }

            if (!m_assets.TryGetValue(m_stack.Peek(), out var asset))
            {
                return null;
            }

            return asset;
        }

        public void Clear()
        {
            m_stack.Clear();
            // 销毁所有界面
            foreach(var item in m_assets)
            {
                Destroy(item.Value.gameObject);
            }
            m_assets.Clear();
        }
    }
}
